import styles from './common.module.scss'
import {useDebounceFn, useRequest, useTitle} from "ahooks";
import {Empty, Spin, Typography} from "antd";
import {QuestionCard} from "../../components/QuestionCard";
import {ListSearch} from "../../components/ListSearch";
import {useEffect, useMemo, useRef, useState} from "react";
import {useSearchParams} from "react-router-dom";
import {getQuestionListService} from "../../services/question";
import {LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY} from "../../constant";

const {Title} = Typography


export const List = () => {
    useTitle('小慕问卷 - 我的问卷')

    const [started, setStarted] = useState(false)
    const [searchParams] = useSearchParams()
    const [list, setList] = useState([])
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    const haveMoreData = total > list.length
    const containerRef = useRef<HTMLDivElement>(null);

    const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
    useEffect(() => {
        setStarted(false)
        setList([])
        setPage(1)
        setTotal(0)
    }, [keyword]);
    // 真正加载
    const {run: load, loading} = useRequest(async () => {
        return await getQuestionListService({
            page,
            pageSize: LIST_PAGE_SIZE,
            keyword
        })
    }, {
        manual: true,
        onSuccess(result) {
            const {list: l = [], total = 0} = result
            setList(list.concat(l))
            setTotal(total)
            setPage(page + 1)
        }
    })
    // 触发加载的函数
    const {run: tryLoadMore} = useDebounceFn(() => {
        const elem = containerRef.current;
        if (elem == null) return
        const domRect = elem.getBoundingClientRect()
        if (domRect == null) return
        const {bottom} = domRect
        if (bottom <= document.body.clientHeight) {
            load()
            setStarted(true)
        }
    }, {wait: 1000})

    useEffect(() => {
        tryLoadMore()
    }, [searchParams])

    useEffect(() => {
        if (haveMoreData) {
            window.addEventListener('scroll', tryLoadMore)
        }
        return () => {
            window.removeEventListener('scroll', tryLoadMore)
        }
    }, [searchParams, haveMoreData])

    const LoadMoreContentElem = useMemo(() => {
        if (!started || loading) return <Spin/>
        if (total === 0) return <Empty description={'暂无数据'}/>
        if (!haveMoreData) return <span>没有更多了...</span>
        return <span>开始加载下一页</span>
    }, [started, loading, haveMoreData])
    return (
        <>
            <div className={styles.header}>
                <div className={styles.left}>
                    <Title level={3}>我的问卷</Title>
                </div>
                <div className={styles.right}>
                    <ListSearch></ListSearch>
                </div>
            </div>
            <div className={styles.content}>
                {list.length > 0 && list.map((q: any) => {
                    const {_id} = q
                    return <QuestionCard {...q} key={_id}/>
                })}
            </div>

            <div className={styles.footer}>
                <div ref={containerRef}>
                    {LoadMoreContentElem}
                </div>
            </div>
        </>
    );
};